package com.myq.note.service.impl;

import com.myq.note.dao.UserDao;
import com.myq.note.po.Result;
import com.myq.note.po.User;
import com.myq.note.service.UserService;
import com.myq.note.util.Md5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    Md5 md5;

    @Autowired
    UserDao userDao;

    @Override
    public Result registerUser(User user) {
        Result<User> result = new Result<>();

        if (userDao.findUser(user.getUsername()) != null){

            result.setMes("用户名重复");
            result.setStatus(100);
            return result;
        }

        String id = UUID.randomUUID().toString();
        user.setUser_id(id);
        String salt = md5.getSalt();
        user.setSalt(salt);
        user.setPassword(md5.getNewPwd(user.getPassword()+salt));
        int i = userDao.registerUser(user);
        if (i>0){
            result.setStatus(100);
        }
        result.setStatus(200);
        return result;
    }

    @Override
    public Result loginUser(User user) {
        Result<User> result = new Result<>();
        User user1 = userDao.findUser(user.getUsername());
        if ( user1 == null){
            result.setMes("用户不存在");
            return result;
        }
        String pwd = md5.getNewPwd(user.getPassword()+user1.getSalt());
        if (pwd.equals(user1.getPassword())){
            result.setStatus(200);
            result.setMes("成功");
            result.setData(user1);
            return result;
        }else {
            result.setMes("密码错误");
            return result;
        }
    }

}
